#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 noet:
#
# $Id: HighlightManager.py 2 2008-06-05 13:15:18Z wejradford $

"""
HighlightManager.py

Handles the applying/removing/re-applying highlights to the 
document based on matches with the engine.
"""

__version__ = "$Revision: 2 $"
# $URL: http://yare-gedit-plugin.googlecode.com/svn/trunk/yare/HighlightManager.py $

import logging

class HighlightManager(object):
	"""
	See module docstring.
	"""
	COLOUR = "yellow"
	def __init__(self, regexEngine, colour=COLOUR):
		self._engine = regexEngine
		self._colour = colour
		self._highlightTag = None

	def apply(self, document):
		"""
		Highlights the engine's matches in the document.
		Returns the number of highlights applied.
		"""
		if not self._engine.isSetup:
			return
		# FIXME - Do we want hidden chars???
		# FIXME - This breaks with utf-16 test - the FFFE BOM...
		text = document.get_text(document.get_start_iter(), document.get_end_iter(), False).decode(document.get_encoding().get_charset())
		logging.info("Applying highlights to the text (length=%d)" % len(text))
		# Highlight matches if there was any setup change.
		nHighlights = 0
		if self._highlightTag is None:
			self._highlightTag = document.create_tag("highlight", background=self._colour)
			index = -1
			for index, match in enumerate(self._engine.finditer(text)):
				startIter = document.get_iter_at_offset(match.start())
				endIter = document.get_iter_at_offset(match.end())
				document.apply_tag(self._highlightTag, startIter, endIter)
			if index > -1:
				nHighlights = index + 1
		return nHighlights

	def remove(self, document):
		"""
		Removes the highlights from document.
		"""
		tagTable = document.get_tag_table()
		print tagTable
		self._highlightTag = tagTable.lookup("highlight")
		if self._highlightTag is not None:
			tagTable.remove(self._highlightTag)
		self._highlightTag = None

	def reapply(self, document):
		self.remove(document)
		return self.apply(document)

# End of $URL: http://yare-gedit-plugin.googlecode.com/svn/trunk/yare/HighlightManager.py $
